<?php
/**
 *RefundServices
 * @author tan bing
 * @date 2021-11-15 11:19
 */


namespace Modules\Order\Services\Api;


use App\Models\Express;
use Illuminate\Http\Request;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\OrderRefund;
use mysql_xdevapi\CollectionModify;

class RefundServices extends BaseService
{

    private Request $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 订单售后浏览页面
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws \Exception
     * @author tan bing
     * @date 2021-11-15 11:28
     */
    public function refundPreview()
    {
        $orderDetailId = $this->request->input('order_detail_id');
        $userId = $this->request->attributes->get('userId');
        $data = OrderDetail::query()
            ->where([
                'order.is_delete' => 0,
                'order.user_id'   => $userId,
                'order_detail.id'       => $orderDetailId,
            ])
            ->leftJoin('goods', 'order_detail.goods_id', '=', 'goods.id')
            ->leftJoin('order', 'order_detail.order_id', '=', 'order.id')
            ->select('order_detail.id AS order_detail_id','goods.id AS goods_id','goods.name','order_detail.goods_attr as attr','order_detail.goods_pic','order_detail.goods_num as num','order_detail.goods_price as total_price','order.pay_price')
            ->first();
        if (!$data) {
            throw new \Exception('订单不存在');
        }
        $data['attr'] = json_decode($data['attr']);
        $data['max_refund_price'] = min($data['total_price'], $data['pay_price']);

        return $data;
    }

    /**
     * 售后订单提交
     * @return OrderRefund
     * @throws \Exception
     * @author tan bing
     * @date 2021-11-15 11:50
     */
    public function refund()
    {
        $type          = $this->request->post('type');
        $desc          = $this->request->post('desc');
        $picList       = $this->request->post('pic_list');
        $orderDetailId = $this->request->post('order_detail_id');
        $userId        = $this->request->attributes->get('userId');
        $order_detail  = OrderDetail::query()->where(['id' => $orderDetailId, 'is_delete' => 0,])->first();
        if (!$order_detail)
            throw new \Exception('订单商品不存在，无法申请售后');

        $order = Order::query()->where(['id' => $order_detail->order_id, 'is_delete' => 0, 'user_id' => $userId,])->first();
        if (!$order)
            throw new \Exception('订单不存在，无法申请售后');

        $orderStatus = [
            1,  // 已支付
            2,  // 已发货
            3,  // 已完成
            6,  // 已完成
        ];
        if (!in_array($order->order_status, $orderStatus))
            throw new \Exception('当前订单状态不满足申请售后条件');

        $existRefund = OrderRefund::query()->where([
            'user_id'         => $userId,
            'order_detail_id' => $orderDetailId,
            'is_delete'       => 0,
        ])->first();

        if ($existRefund)
            throw new \Exception('该商品已申请过售后，请不要重复申请');

        $refund = new OrderRefund();
//        $refund->store_id = 0;
        $refund->user_id         = $userId;
        $refund->order_id        = $order->id;
        $refund->order_detail_id = $order_detail->id;
        $refund->refund_type     = $type;
        $refund->order_refund_no = $this->getOrderRefundNo();

        if ($refund->refund_type == 1) {
            $refund->refund_price = min($order->pay_price, $order_detail->goods_price);

        } elseif ($refund->refund_type == 2) {
            $refund->refund_price = 0;
        }
        $refund->user_desc     = $desc;
        $refund->pic_list      = $picList;//json_encode();
        $refund->refund_status = 0;

        if (!$refund->save())
            throw new \Exception('售后申请提交失败');

        // TODO 售后申请提交成功的相关操作

        return $refund;
    }

    public function refundDetail()
    {
        $orderRefundId = $this->request->input('order_refund_id');
        $order_refund = OrderRefund::query()
            ->where([
                'order_refund.id' => $orderRefundId,
                'order_refund.is_delete' => 0,
            ])
            ->leftJoin('order_detail', 'order_refund.order_detail_id', '=', 'order_detail.id')
            ->leftJoin('goods', 'order_detail.goods_id', '=', 'goods.id')
            ->leftJoin('refund_address','order_refund.refund_address_id', '=', 'refund_address.id')
            ->select('order_refund.id AS order_refund_id','goods.id AS goods_id','goods.name','order_detail.goods_num AS num','order_detail.goods_pic','order_detail.goods_price AS total_price','order_detail.goods_attr  AS attr','order_refund.user_desc AS refund_desc','order_refund.refund_type','order_refund.refund_status','order_refund.pic_list AS refund_pic_list','order_refund.refund_price','order_refund.is_agree','order_refund.is_user_send','order_refund.user_send_express','order_refund.user_send_express_no','refund_address.name as re_name','refund_address.mobile as re_mobile','refund_address.address as re_address')
            ->first();

        if (!$order_refund)
            throw new \Exception('售后单不存在');

        $order_refund['attr'] = json_decode($order_refund['attr']);
        $order_refund['refund_pic_list'] = json_decode($order_refund['refund_pic_list'], true);
        $order_refund['express_list'] = Express::get();
        $order_refund['order_refund_status_bg'] = asset('modules/order/images/order-refund-status-bg.png');

        return $order_refund;
    }

    /**
     * 用户提交售后订单发货
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws \Exception
     * @author tan bing
     * @date 2021-11-15 15:25
     */
    public function refundSend()
    {
        $orderRefundId = $this->request->post('order_refund_id');
        $express       = $this->request->post('express');
        $expressNo     = $this->request->post('express_no');
        $userId        = $this->request->attributes->get('userId');
        $order_refund = OrderRefund::query()->where(['id' => $orderRefundId, 'user_id' => $userId])->first();
        if (!$order_refund)
            throw new \Exception('售后订单不存在。');

        $order_refund->is_user_send = 1;
        $order_refund->user_send_express = $express;
        $order_refund->user_send_express_no = $expressNo;
        if (!$order_refund->save())
            throw new \Exception('发货失败');

        return $order_refund;
    }

    /**
     * 获取售后单号
     * @return string|null
     * @author tan bing
     * @date 2021-11-15 11:38
     */
    private function getOrderRefundNo()
    {
        $order_refund_no = null;
        while (true) {
            $order_refund_no = date('YmdHis') . mt_rand(100000, 999999);
            $exist_order_refund_no = OrderRefund::query()->where(['order_refund_no' => $order_refund_no])->exists();
            if (!$exist_order_refund_no) {
                break;
            }
        }

        return $order_refund_no;
    }
}